#!/bin/bash -ex
# SPDX-License-Identifier: LGPL-2.1+

DIGEST=${1:-sha512-256}
PARAMS="-v --digest=$DIGEST"

export CASYNC_PROTOCOL_PATH=@top_builddir@

SCRATCH_DIR=${TMPDIR:-/var/tmp}/test-casync.$RANDOM
mkdir -p $SCRATCH_DIR

dd if=/dev/urandom of=$SCRATCH_DIR/blob bs=102400 count=80

@top_builddir@/casync $PARAMS digest $SCRATCH_DIR/blob > $SCRATCH_DIR/test.digest
@top_builddir@/test-calc-digest $DIGEST $SCRATCH_DIR/blob > $SCRATCH_DIR/test.digest2

@top_builddir@/casync $PARAMS make $SCRATCH_DIR/test.caibx $SCRATCH_DIR/blob
@top_builddir@/casync $PARAMS digest $SCRATCH_DIR/test.caibx > $SCRATCH_DIR/test.caibx.digest

diff -q $SCRATCH_DIR/test.digest $SCRATCH_DIR/test.digest2
diff -q $SCRATCH_DIR/test.digest $SCRATCH_DIR/test.caibx.digest

@top_builddir@/casync $PARAMS extract $SCRATCH_DIR/test.caibx $SCRATCH_DIR/blob2
@top_builddir@/casync $PARAMS extract $SCRATCH_DIR/test.caibx --seed=$SCRATCH_DIR/blob2 $SCRATCH_DIR/blob3

@top_builddir@/test-calc-digest $DIGEST $SCRATCH_DIR/blob2 > $SCRATCH_DIR/extract.digest
@top_builddir@/test-calc-digest $DIGEST $SCRATCH_DIR/blob3 > $SCRATCH_DIR/extract2.digest

diff -q $SCRATCH_DIR/test.digest $SCRATCH_DIR/extract.digest
diff -q $SCRATCH_DIR/test.digest $SCRATCH_DIR/extract2.digest

if [ $UID = 0 ]; then
    modprobe nbd ||:

    if [ -e /dev/nbd0 -a ${CASYNC_TEST_NBD:-1} = 1 ]; then
        MKDEV_PID=`@top_builddir@/notify-wait @top_builddir@/casync $PARAMS mkdev $SCRATCH_DIR/test.caibx $SCRATCH_DIR/test-node`

        dd if=$SCRATCH_DIR/test-node bs=102400 count=80 | @top_builddir@/test-calc-digest $DIGEST > $SCRATCH_DIR/mkdev.digest

        diff -q $SCRATCH_DIR/test.digest $SCRATCH_DIR/mkdev.digest

        kill $MKDEV_PID
    fi
fi

rm -rf $SCRATCH_DIR
